import React, { FC, KeyboardEvent, ReactElement, useRef } from 'react'

import { todoType } from '@/apis'
import { addTodo } from '@/store'

import less from './style.module.less'


const Header: FC = (): ReactElement => {

  const inputRef = useRef<HTMLInputElement>(null)

  const handleKeyUp = (e: KeyboardEvent<HTMLInputElement>): void => {
    const { key } = e
    if (key !== 'Enter') return

    // 获取input的输入值
    const val: string = inputRef.current!.value.trim()

    if (val === '') {
      alert('todo内容不能为空')
      return
    }

    const todoObj: todoType = { id: +new Date(), content: val, done: false }
    addTodo(todoObj)  // 新增todo

    inputRef.current!.value = ''
  }

  return (
    <div className={less.header}>
      <h2>TodoList</h2>
      <input
        type="text"
        placeholder="在此处输入任务名称，按回车键确认"
        ref={inputRef}
        onKeyUp={e => handleKeyUp(e)} />
    </div>
  )
}

export default Header
